package com.servlet;

import com.Imp.MerchantMapperImpl;
import com.Imp.UserMapperImpl;
import com.entity.Merchant;
import com.entity.User;
import com.mapper.MerchantMapper;
import com.mapper.UserMapper;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class MerchantController extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request,response);
    }

    public void  doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException{
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        HttpSession session = request.getSession();
        String merchantId = (String) session.getAttribute("username");
        //获取所有登录数据
        String name=(String)request.getParameter("name");
        String gender=(String)request.getParameter("gender");
        String age=(String)request.getParameter("age");
        String phoneNumber=(String)request.getParameter("phoneNumber");

        //根据用户账户获取到商家信息
        MerchantMapper merchantMapper = new MerchantMapperImpl();
        Merchant merchant = merchantMapper.getMerchantBymerchantId(merchantId);
        UserMapper userMapper = new UserMapperImpl();
        User user = userMapper.getUserByUsername(merchantId);
        if(merchant == null){
            merchant = new Merchant();
            merchant.setName(name);
            merchant.setMerchantId(merchantId);
            merchant.setSex(gender);
            merchant.setPassWord(user.getPassWord());
            merchant.setAge(age);
            merchant.setPhone(phoneNumber);
            //将更改后的信息插入数据库中
            merchantMapper.addMerchant(merchant);
            response.sendRedirect("information_merchant.jsp");
        }
        else{
            merchant.setName(name);
            merchant.setSex(gender);
            merchant.setAge(age);
            merchant.setPhone(phoneNumber);
            //将更改后的信息插入数据库中
            merchantMapper.updateMerchant(merchant);
            response.sendRedirect("information_merchant.jsp");
        }
    }
}
